<template>
  <div>
    <el-drawer
      :title="`入库单详情（${detailData.stockInCode}）`"
      :visible.sync="visible"
      :append-to-body="true"
      :destroy-on-close="true"
      size="75%"
    >
      <!-- 左右布局 -->
      <div class="center">

        <!-- 左侧 -->
        <div class="left">
          <el-descriptions title="基本信息" :label-style="{fontSize:'14px'}" :content-style="{fontSize:'14px'}">
            <el-descriptions-item label="入库类型">{{ detailData.stockInType && formatColumnMap(stockInTypeMap, 'value', detailData.stockInType, 'desc') }}</el-descriptions-item>
            <el-descriptions-item label="调出仓库">{{ detailData.fromStoreName }}</el-descriptions-item>
            <el-descriptions-item label="调入仓库">{{ detailData.storeName }}</el-descriptions-item>
            <el-descriptions-item label="调拨车辆">{{ detailData.carNumber }}</el-descriptions-item>
            <el-descriptions-item label="司机">{{ detailData.operator }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ parseTime(detailData.createTime , '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
            <el-descriptions-item v-if="detailData.stockInType===5" label="入库人">{{ detailData.createUser }}</el-descriptions-item>
            <el-descriptions-item label="创建人">{{ detailData.createUser }}</el-descriptions-item>
            <el-descriptions-item label="备注">{{ detailData.remark }}</el-descriptions-item>
            <el-descriptions-item v-if="detailData.stockInType===5" label="入库时间">{{ parseTime(detailData.enterDt , '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
            <el-descriptions-item v-if="detailData.stockInType===5" label="配送员">{{ detailData.ownerName }}</el-descriptions-item>
          </el-descriptions>
          <!-- 表格 -->
          <div class="title">入库列表<span v-if="detailData.scanType">（{{ detailData.scanType===1?'按商品扫码':'混合扫码' }}）</span></div>
          <lb-table
            id="lbTable"
            ref="lbTable"
            border
            highlight-current-row
            element-loading-text="加载中"
            :data="tableData.data"
            :column="tableData.column"
            show-summary
            :summary-method="getSummaries"
            :immediate-fetch="false"
            :pagination="false"
            :max-height="300"
          />
          <div v-if="detailData.stockInType!==5" class="settlement">本次入库<span v-for="(item,index) in sumObj" v-show="item.sum" :key="index">{{ `${item.name}瓶小计${item.sum}，` }}</span>合计{{ allSum }}瓶</div>
        </div>
        <!-- 右侧 -->
        <div class="right">
          <span>流转信息：</span>
          <el-timeline :reverse="reverse">
            <el-timeline-item v-for="(item, index) in flowInfoData" :key="index" :timestamp="`${parseTime(item.happendDt, '{y}-{m}-{d} {h}:{i}')} ${item.operator}`" placement="top">
              <el-card>
                <h4>{{ item.traceDesc }}</h4>
                <h4 v-if="item.marker" style="color: red;">{{ `${item.marker}` }}</h4>
                <p>{{ `发生部门&nbsp;——&nbsp;${item.orgName ? item.orgName : '系统'}` }}</p>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </el-drawer>
    <scanCodesDetail ref="scanCodesDetail" :gd-status-map="gdStatusMap" />
    <abnormalDetail ref="abnormalDetail" :gd-status-map="gdStatusMap" />
    <mixedabnormalDetail ref="mixedabnormalDetail" :detail-data="detailData" :gd-status-map="gdStatusMap" :good-count="allSum" :scan-count="detailData.scanCount" />
    <mixedScanningCodeDetail ref="mixedScanningCodeDetail" :detail-data="detailData" :gd-status-map="gdStatusMap" :good-count="allSum" :scan-count="detailData.scanCount" />
  </div>
</template>

<script>
  import { commonTansferInfo, queryStockInBillDetail } from '@/api'
  import moment from 'dayjs'
  import { formatColumnMap } from '@/utils'
  import { parseTime } from '@/utils'
  import scanCodesDetail from './scanCodesDetail'
  import mixedScanningCodeDetail from './mixedScanningCodeDetail'
  import mixedabnormalDetail from './mixedabnormalDetail'
  import abnormalDetail from './abnormalDetail'

  export default {
    name: 'merchantSide-OrderDetails',
    components: {
      scanCodesDetail,
      mixedScanningCodeDetail,
      abnormalDetail,
      mixedabnormalDetail
    },
    props: {
      stockInTypeMap: {
        type: Array,
        required: true
      },
      gdStatusMap: {
        type: Array,
        required: true
      }
    },
    data() {
      return {
        moment,
        formatColumnMap,
        parseTime,
        visible: false,
        reverse: false,
        payStatusMap: [],
        paymentMethodMap: [],
        detailData: {},
        flowInfoData: [], // 流转信息
        sumObj: [],
        allSum: 0,
        tableData: {
          column: [
            {
              type: 'index',
              width: 60
            },
            {
              prop: 'goodsName',
              label: '商品名称',
              minWidth: 100,
              showOverflowTooltip: true
            },
            {
              prop: 'gdStatus',
              label: '状态',
              minWidth: 85,
              render: (h, { row }) => <span>{row.gdStatus && formatColumnMap(this.gdStatusMap, 'value', row.gdStatus, 'desc') }</span>
            },
            {
              prop: 'gdCount',
              label: '申请数量',
              minWidth: 50
            },
            {
              prop: 'realCount',
              label: '扫码数量',
              minWidth: 70,
              render: (h, { row, $index }) => row.realCount ? <el-link underline={false} onClick={() => this.openScanCode(row, $index)}>{row.realCount}</el-link> : <span>-</span>
            },
            {
              prop: 'abnormalCount',
              label: '异常数量',
              minWidth: 50,
              render: (h, { row, $index }) => row.abnormalCount ? <el-link underline={false} onClick={() => this.openAbnormalCount(row)}>{row.abnormalCount}</el-link> : <span>-</span>
            }
          ],
          data: []
        }
      }
    },
    computed: {
    },
    methods: {
      open(temp) {
        return new Promise(async(resolve) => {
          this.resolve = resolve
          // console.log(temp)
          if (temp.stockInCode) {
            this.temp = temp
            await this.getStockInBillDetail(temp)
          }
        })
      },
      async getStockInBillDetail(temp) {
        const [res, res1] = await Promise.all([
          queryStockInBillDetail({ stockInCode: temp.stockInCode }),
          commonTansferInfo({ billCode: temp.stockInCode, billType: 8192 })
        ])
        if (res.data) {
          this.detailData = res.data
          this.tableData.data = res.data.detailList
        }
        if (res1.data) {
          this.flowInfoData = res1.data
        }
        this.sumObj = []
        this.gdStatusMap.forEach(item => {
          const obj = {
            name: item.desc,
            sum: 0
          }
          const values1 = this.tableData.data.map(i => {
            if (i.gdStatus === item.value) {
              return Number(i.gdCount)
            } else {
              return 0
            }
          })
          obj.sum = values1.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }) || 0
          this.sumObj.push(obj)
        })
        this.allSum = 0
        this.sumObj.forEach(item => {
          this.allSum += item.sum
        })
        this.visible = true
      },
      // 合计
      getSummaries(param) {
        const { columns, data } = param
        const sums = []
        columns.forEach((column, index) => {
          if (index === 0 || index === 2) {
            sums[index] = ''
            return
          }
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] += ''
            setTimeout(() => {
              const a = document.getElementById('lbTable').querySelector('.el-table__footer').querySelectorAll('td')[4].querySelector('.cell')
              if (index === 4 && this.detailData.scanType === 2) {
                const that = this
                sums[index] = this.detailData.scanCount
                this.$nextTick(() => {
                  const html = `<el-link underline style="color:#126edc;cursor: pointer;">${sums[index]}</el-link>`
                  a.innerHTML = html
                  a.onclick = function() { that.openScanCode() }
                })
              }
              if (index === 4 && sums[index] !== '0' && this.detailData.scanType === 1) {
                const that = this
                this.$nextTick(() => {
                  const html = `<el-link underline style="color:#126edc;cursor: pointer;">${sums[index]}</el-link>`
                  a.innerHTML = html
                  a.onclick = function() { that.openScanCode({ stockInCode: that.detailData.stockInCode }) }
                })
              }
              const b = document.getElementById('lbTable').querySelector('.el-table__footer').querySelectorAll('td')[5].querySelector('.cell')
              if (index === 5 && this.detailData.scanType === 2) {
                const that = this
                sums[index] = this.detailData.abnormalTotalCount
                this.$nextTick(() => {
                  const html = `<el-link underline style="color:#126edc;cursor: pointer;">${sums[index]}</el-link>`
                  b.innerHTML = html
                  b.onclick = function() { that.openAbnormalCount(that.detailData) }
                })
              }
              if (index === 5 && sums[index] !== '0' && this.detailData.scanType === 1) {
                const that = this
                this.$nextTick(() => {
                  const html = `<el-link underline style="color:#126edc;cursor: pointer;">${sums[index]}</el-link>`
                  b.innerHTML = html
                  b.onclick = function() { that.openAbnormalCount(that.detailData) }
                })
              }

              if ((index === 4 || index === 5) && this.detailData.scanType === 0) {
                sums[index] = '-'
              }
            }, 600)
          } else {
            sums[index] = '合计'
          }
        })
        return sums
      },
      // 打开扫码
      openScanCode(row) {
        // console.log(row)
        if (this.detailData.scanType === 2) {
          this.$refs.mixedScanningCodeDetail.open(this.detailData.stockInCode, this.detailData)
        } else {
          this.$refs.scanCodesDetail.open(row.stockInCode, row)
        }
      },
      openAbnormalCount(row) {
        console.log(row, this.detailData)
        if (this.detailData.scanType === 2) {
          this.$refs.mixedabnormalDetail.open(this.detailData.stockInCode, this.detailData)
        } else {
          this.$refs.abnormalDetail.open(row)
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
.center {
  display: flex;
  height: 500px;
  padding: 0 20px;
  font-size: 14px;
  font-weight: 400;
  color: #333;
  text-align: left;

  .left {
    position: relative;
    width: 750px;
    height: 100%;
    /deep/ .el-descriptions__title {
      font-size: 15px;
      color: #38BDBD;
    }

    .title {
      margin-bottom: 20px;
      font-size: 15px;
      font-weight: 700;
      color: #38BDBD;
    }
    .settlement {
      margin-top: 20px;
      font-size: 16px;
      font-weight: 700;
      color: #F00;
    }

    .el-table {
      margin-bottom: 20px;
    }

    .el-descriptions {
      margin-bottom: 20px;
    }

    img {
      width: 61px;
      height: 61px;
      margin-left: 80px;
    }
  }

  .right {
    height: 100%;
    margin-left: 15px;
    flex: 1;

    span {
      display: block;
      height: 24px;
      padding-left: 20px;
      font-weight: 700;
      line-height: 24px;
      color: white;
      background-color: #38BDBD;
      border-radius: 5px;
    }

    .el-timeline {
      margin-top: 20px;
    }
  }
}
</style>
